import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, In } from 'typeorm';
import { Task } from './entities/task.entity';
import { CreateTaskDto } from './dto/create-task.dto';
import { UpdateTaskDto } from './dto/update-task.dto';
import { User } from '../users/entities/user.entity';
import { Category } from '../categories/entities/category.entity';
import { Tag } from '../tags/entities/tag.entity';

@Injectable()
export class TasksService {
  constructor(
    @InjectRepository(Task)
    private tasksRepository: Repository<Task>,
    @InjectRepository(Category)
    private categoriesRepository: Repository<Category>,
    @InjectRepository(Tag)
    private tagsRepository: Repository<Tag>,
  ) {}

  async create(createTaskDto: CreateTaskDto, user: User): Promise<Task> {
    const { title, description, completed, dueDate, categoryId, tagIds } =
      createTaskDto;

    // 创建任务对象
    const task = new Task();
    task.title = title;
    task.description = description || null;
    task.completed = completed || false;
    task.dueDate = dueDate ? new Date(dueDate) : null;
    task.user = user;

    // 添加分类
    if (categoryId) {
      const category = await this.categoriesRepository.findOne({
        where: { id: categoryId, user: { id: user.id } },
      });

      if (category) {
        task.category = category;
      }
    }

    // 保存任务以获取ID
    const savedTask = await this.tasksRepository.save(task);

    // 添加标签
    if (tagIds && tagIds.length > 0) {
      const tags = await this.tagsRepository.findBy({
        id: In(tagIds),
        user: { id: user.id },
      });

      if (tags.length > 0) {
        savedTask.tags = tags;
        await this.tasksRepository.save(savedTask);
      }
    }

    return this.findOne(savedTask.id, user);
  }

  async findAll(user: User): Promise<Task[]> {
    return this.tasksRepository.find({
      where: { user: { id: user.id } },
      relations: ['category', 'tags'],
      order: { createdAt: 'DESC' },
    });
  }

  async findOne(id: number, user: User): Promise<Task> {
    const task = await this.tasksRepository.findOne({
      where: { id, user: { id: user.id } },
      relations: ['category', 'tags'],
    });

    if (!task) {
      throw new NotFoundException(`ID为 ${id} 的任务不存在`);
    }

    return task;
  }

  async update(
    id: number,
    updateTaskDto: UpdateTaskDto,
    user: User,
  ): Promise<Task> {
    const task = await this.findOne(id, user);
    const { title, description, completed, dueDate, categoryId, tagIds } =
      updateTaskDto;

    if (title !== undefined) task.title = title;
    if (description !== undefined) task.description = description || null;
    if (completed !== undefined) task.completed = completed;
    if (dueDate !== undefined)
      task.dueDate = dueDate ? new Date(dueDate) : null;

    // 更新分类
    if (categoryId !== undefined) {
      if (categoryId === null) {
        task.category = null;
      } else {
        const category = await this.categoriesRepository.findOne({
          where: { id: categoryId, user: { id: user.id } },
        });

        if (category) {
          task.category = category;
        }
      }
    }

    // 更新标签
    if (tagIds !== undefined) {
      if (tagIds.length === 0) {
        task.tags = [];
      } else {
        const tags = await this.tagsRepository.findBy({
          id: In(tagIds),
          user: { id: user.id },
        });

        task.tags = tags;
      }
    }

    return this.tasksRepository.save(task);
  }

  async remove(id: number, user: User): Promise<void> {
    const task = await this.findOne(id, user);
    await this.tasksRepository.remove(task);
  }
}
